using System.Diagnostics;
using System.Linq;
using System.Threading;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyCompany.WebCrawler.Domain;
using MyCompany.WebCrawler.Repositories;
using MyCompany.WebCrawler.Tasks;

namespace MyCompany.WebCrawler.Test.Domain.ThreadingTests
{
    [TestClass]
    public class StartBusinessThreadTest
    {
        private ThreadManager manager;

        [TestInitialize]
        public void Setup()
        {
            // TODO: mock DownloadPage and provide hardcoded pages
            using (var db = new CrawlerContext())
            {
                db.Database.ExecuteSqlCommand("DELETE FROM Urls");
            }

            var repository = new Repository();
            var factory = new TasksFactory(new Downloader(), new WebCrawler.Domain.UiFetcher(), repository);
            manager = new ThreadManager(repository);

            repository.Queue.Enqueue(factory.CreateGetLinks("http://google.com"));
            repository.Queue.Enqueue(factory.CreateMoreTasksToDownload());

        }

        [TestMethod]
        public void StartBusinessThread()
        {
            manager.Start(1);
            Trace.WriteLine("Waiting for 1 minutes... Just to have a lot of links in our real database.");
            Thread.Sleep(60000);
            manager.Wait();

            GetLinksCount().Should().BeGreaterThan(1);
        }

        [TestMethod]
        public void StartBusinessThreads()
        {
            manager.Start(3);
            Trace.WriteLine("Waiting for 1 minutes... Just to have a lot of links in our real database.");
            Thread.Sleep(60000);
            manager.Wait();

            GetLinksCount().Should().BeGreaterThan(1);
        }

        private static int GetLinksCount()
        {
            using (var db = new CrawlerContext())
            {
                var count = (from o in db.Urls select o).Count();

                Trace.WriteLine("Database: " + count);
                return count;
            }
        }
    }
}